package org.restorator.controller;

import com.google.gson.Gson;
import org.restorator.entity.Order;
import org.restorator.entity.Table;
import org.restorator.service.TableService;
import org.restorator.service.impl.TableServiceImpl;
import org.restorator.utill.ControllerUtil;
import org.restorator.utill.GeneralUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * Controller for work with REST style bulk requests on entity {@link Table} by it's id.
 *
 * @author Snisar Bogdan.
 */
@WebServlet(name = "table", urlPatterns = "/table/*")
public class TableController extends HttpServlet {

    private static Logger logger = LoggerFactory.getLogger(GeneralUtil.getClassName());

    @Override
    public void init() throws ServletException {
        super.init();
        tableService = new TableServiceImpl();
    }

    private TableService tableService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String urlStringEnd = ControllerUtil.getUrlIdMatch(req, resp);
            Integer orderId = Integer.parseInt(urlStringEnd);
            logger.trace("Get request. Try fained  table by id: {}", orderId);
            Table table = tableService.get(orderId);

            if(table != null) {
                ControllerUtil.printOk(resp, tableService.toDto(table));
            } else {
                ControllerUtil.printError(resp);
            }
        } catch (Exception e) {
            logger.error("Exception in request processing: {}. \nStack trace: {}", e.getMessage(), e);
//            if exception - send 404 error
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doDelete(req, resp);    //To change body of overridden methods use File | Settings | File Templates.
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);    //To change body of overridden methods use File | Settings | File Templates.
    }
}
